<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新增园区' : '编辑园区') + ''"
    width="1000px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
    <tdMap
      :isShowCreateDialog.sync="mapShow"
      :data="mapData"
      @close="handleMpclose"
      @result="getLatlng"
    >
    </tdMap>
    <operate2
      :visible.sync="gdMapOpVisible"
      @close="closedMapop"
      :data="pointData"
      @result="getArr"
    ></operate2>
  </zeda-dialog>
</template>

<script>
import { getDetail, add, edit } from "@/api/park/parkmsg.js";
import {
  deepClone,
  replaceDigit,
  replaceInteger,
  dealElectricity,
} from "@/utils/index";

import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import tdMap from "@/components/netWorkmap/map";
import tableCom from "@/views/configuration/park/parkmsg/components/tableCom.vue";
import operate2 from "@/views/configuration/park/parkmsg/components/operate2.vue";

export default {
  dicts: [],
  components: {
    FormButton,
    CascaderSelect,
    tdMap,
    tableCom,
    operate2,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      gdMapOpVisible: false,
      mapShow: false,
      mapData: {
        lat: "",
        lng: "",
      },
      // 坐标集-电子围栏
      pointData: [],
      loading: false, // 按钮加载中判断
      areaProps: {
        value: "areaId",
        children: "children",
        label: "name",
        checkStrictly: false,
        expandTrigger: "hover",
      },
      querParams: {
        provinceCityDistrictName: "", // 省市区名称
        provincialId: null, // 省id
        cityId: null, // 市id
        districtId: null, // 区id
      },
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 2,
              middle: true,
            },
            rules: {
              name: [
                {
                  required: true,
                  message: "请输入园区名称",
                  trigger: "blur",
                },
                {
                  validator: function (rule, value, callback) {
                    let reg = new RegExp(
                      "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                    );
                    if (!reg.test(value)) {
                      callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur",
                },
              ],
              areaId: [
                {
                  required: true,
                  message: "请选择省市区",
                  trigger: "change",
                },
              ],
              address: [
                {
                  required: true,
                  message: "请输入详细地址",
                  trigger: "blur",
                },
                {
                  validator: function (rule, value, callback) {
                    let reg = new RegExp(
                      "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                    );
                    if (!reg.test(value)) {
                      callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur",
                },
              ],
              completeDate: [
                {
                  required: false,
                  message: "请选择竣工日期",
                  trigger: "change",
                },
              ],
              longitude: [
                {
                  required: true,
                  message: "请输入或选择经度",
                  trigger: ["blur", "change"],
                },
              ],
              latitude: [
                {
                  required: true,
                  message: "请输入或选择纬度",
                  trigger: ["blur", "change"],
                },
              ],
              landArea: [
                {
                  required: false,
                  message: "请输入正确的用地面积",
                  trigger: "blur",
                },
              ],
              buildArea: [
                {
                  required: false,
                  message: "请输入正确的建筑面积",
                  trigger: "blur",
                },
              ],
              concatUser: [
                {
                  required: false,
                  message: "请输入正确的联系人",
                  trigger: "blur",
                },
              ],
              concatPhone: [
                {
                  required: false,
                  pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                  message: "请输入正确的联系电话",
                  trigger: "blur",
                },
              ],
              phone: [
                {
                  required: false,
                  pattern:
                    /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/,
                  message: "请输入正确的座机号",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            name: {
              label: "园区名称",
              maxlength: 30,
              typeName: "el-input",
              placeholder: "请输入园区名称",
            },
            areaId: {
              label: "省市区",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      value={that.$refs?.form?.getFieldsValue().areaId}
                      values={that.$refs?.form?.getFieldsValue().areaId}
                      varient={"areaTree"}
                      showAllLevels={true}
                      propOptions={that.areaProps}
                      size={"small"}
                      placeholder={"请选择省市区"}
                      onInput={(value, label) => {
                        that.setVal(value, "areaId");
                        if (label.length > 0) {
                          that.querParams.provinceCityDistrictName = "";
                          label.map((item) => {
                            that.querParams.provinceCityDistrictName += item;
                          });
                        }
                      }}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            address: {
              label: "详细地址",
              typeName: "el-input",
              maxlength: 50,
              placeholder: "请输入详细地址",
            },
            completeDate: {
              label: "竣工日期",
              typeName: "el-date-picker",
              type: "date",
              size: "small",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择竣工日期",
            },
            longitude: {
              label: "经度(定点)",
              maxlength: 15,
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入或选择经度"
                    maxlength="15"
                    clearable
                    size="small"
                    value={that.$refs?.form?.getFieldsValue().longitude}
                    onInput={(val) => {
                      if (val <= 180) {
                        this.$refs?.form?.setFieldValue("longitude", val);
                      }
                    }}
                  >
                    <template slot="append">
                      <el-button
                        size="small"
                        onClick={() => that.handleMapopen()}
                      >
                        地图
                      </el-button>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            latitude: {
              label: "纬度(定点)",
              maxlength: 15,
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入或选择纬度"
                    maxlength="15"
                    clearable
                    size="small"
                    value={that.$refs?.form?.getFieldsValue().latitude}
                    onInput={(val) => {
                      if (val <= 90) {
                        this.$refs?.form?.setFieldValue("latitude", val);
                      }
                    }}
                  >
                    <template slot="append">
                      <el-button
                        size="small"
                        onClick={() => that.handleMapopen()}
                      >
                        地图
                      </el-button>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            landArea: {
              label: "用地面积",
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入用地面积"
                    clearable
                    size="small"
                    maxlength="10"
                    value={that.$refs?.form?.getFieldsValue().landArea}
                    onInput={(val) => that.replaceDigitDeal(val, 2, "landArea")}
                  >
                    <template slot="append">
                      <span>㎡</span>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            buildArea: {
              label: "建筑面积",
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入建筑面积"
                    clearable
                    size="small"
                    maxlength="10"
                    value={that.$refs?.form?.getFieldsValue().buildArea}
                    onInput={(val) =>
                      that.replaceDigitDeal(val, 2, "buildArea")
                    }
                  >
                    <template slot="append">
                      <span>㎡</span>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            coordinates: {
              label: "坐标集",
              render: (h) => {
                let that = this;
                let a = (
                  <el-button
                    onClick={() => {
                      that.gdMapOpVisible = true;
                    }}
                  >
                    地图绘制
                  </el-button>
                );
                return a;
              },
            },
            tableChise: {
              bsColumn: {
                col: 1,
                middle: true,
              },
              render: (h) => {
                let that = this;
                let a;
                if (that.pointData.length > 0) {
                  a = <tableCom pointData={that.pointData}></tableCom>;
                } else {
                  a = <div>请选取坐标集区域</div>;
                }
                return a;
              },
            },
            concatUser: {
              label: "联系人",
              maxlength: 8,
              typeName: "el-input",
              placeholder: "请输入联系人",
            },
            concatPhone: {
              label: "联系电话",
              typeName: "el-input",
              placeholder: "请输入联系电话",
            },
            phone: {
              label: "座机号",
              typeName: "el-input",
              maxlength: 12,
              placeholder: "请输入座机号",
            },
            remarks: {
              label: "备注",
              typeName: "el-input",
              type: "textarea",
              rows: 4,
              maxlength: 200,
              placeholder: "请输入备注",
            },
          },
        },
      },
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          console.log(this.id);
          if (String(this.id).length > 0) {
            this.getInfo();
          }
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    getArr(data) {
      console.log(data);
      this.pointData = data;
    },
    closedMapop() {
      this.gdMapOpVisible = false;
    },
    getInfo() {
      getDetail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.areaId = res?.data?.districtId;
          this.querParams = {
            provinceCityDistrictName: res?.data?.provinceCityDistrictName,
            provincialId: res?.data?.provincialId,
            cityId: res?.data?.cityId,
            districtId: res?.data?.districtId,
          };
          newData.landArea = dealElectricity(
            res?.data?.landArea ?? 0,
            100,
            2,
            "number"
          );
          newData.buildArea = dealElectricity(
            res?.data?.buildArea ?? 0,
            100,
            2,
            "number"
          );
          this.pointData = JSON.parse(newData.coordinates);
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!401004");
        });
    },
    setVal(value, key) {
      if (key === "areaId") {
        this.querParams.provincialId = value[0];
        this.querParams.cityId = value[1];
        this.querParams.districtId = value[2];
        this.$refs?.form?.setFieldValue("areaId", value);
      }
    },
    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      let query = {
        ...data,
        ...this.querParams,
        coordinates: JSON.stringify(this.pointData),
      };
      query.landArea = Number(query?.landArea ?? 0) * 100;
      query.buildArea = Number(query?.buildArea ?? 0) * 100;
      // 坐标集处理
      // query.coordinates
      query.tableChise = null;
      console.log(query, "query");
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(query);
          } else {
            this.addRequest(query);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      add(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!401002");
        });
    },
    editRequest(data) {
      edit(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!401003");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.pointData = [];
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /* 经纬度地图 */
    handleMapopen() {
      this.mapShow = true;
    },
    handleMpclose(status) {
      this.mapShow = false;
    },
    getLatlng(e) {
      const { lat, lng } = e;
      this.$refs?.form?.setFieldValue("latitude", lat.toFixed(7));
      this.$refs?.form?.setFieldValue("longitude", lng.toFixed(7));
    },
    /* 输入限制 */
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      // this.form[flage] = replaceDigit(val, dit);
      let result = replaceDigit(val, dit);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      // this.form[flage] = replaceInteger(val);
      let result = replaceInteger(val);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 坐标集
    amapgetLatlng(e) {
      let lat = e[0].position[1];
      let lng = e[0].position[0];
      this.pointData.push({
        lat,
        lng,
        clock: false,
        range: "",
      });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
